/*	BuildMarine class definition.
 *
*/

#include "BuildMarine.h"

void BuildMarine::Enter()
{
	DEBUG_PRINT("BuildMarine(%p) %s entering\n", this, GetName().c_str());

}

void BuildMarine::Execute()
{
	DEBUG_PRINT("BuildMarine(%p) %s executing\n", this, GetName().c_str());
	std::list<Base*>* bases = BB->GetBases();
	std::list<BWAPI::Unit*>* barracksList;
	BWAPI::Unit* bar = NULL;
	for(std::list<Base*>::iterator base = bases->begin(); base != bases->end(); base++)
	{
		barracksList = (*base)->GetBuildingsByType(BWAPI::UnitTypes::Terran_Barracks);
		if(barracksList)
		{
			for(std::list<BWAPI::Unit*>::iterator it = barracksList->begin(); it != barracksList->end(); it++)
			{
				if (!(*it)->isTraining() && !(*it)->isBeingConstructed())
					bar = *it;
			}
			if (bar) 
			{
				BB->SpendResources(BWAPI::UnitTypes::Terran_Marine);
				bar->train(BWAPI::UnitTypes::Terran_Marine);
			}
		}
	}
	control->FinishWithSuccess();
}

void BuildMarine::Exit()
{
	DEBUG_PRINT("BuildMarine(%p) %s exiting\n", this, GetName().c_str());

}

bool BuildMarine::CheckConditions()
{
	DEBUG_PRINT("BuildMarine(%p) %s checking conditions\n", this, GetName().c_str());
	std::list<BWAPI::Unit*>* bar = BB->GetBuildingsByTypeGeneral(BWAPI::UnitTypes::Terran_Barracks);
	std::list<BWAPI::Unit*>* academy = BB->GetBuildingsByTypeGeneral(BWAPI::UnitTypes::Terran_Academy);
	std::list<BWAPI::Unit*>* marines = BB->GetUnitsByTypeGeneral(BWAPI::UnitTypes::Terran_Marine);
	if(!academy)
	{
		if(marines)
		{
			if(marines->size() < 6)
			{
				if(BB->isBuildUnit(BWAPI::UnitTypes::Terran_Marine) )
				{
					DEBUG_PRINT("BuildMarine(%p) %s checked conditions and has %d minerals to spend\n", this, GetName().c_str(), BB->GetMineralsToSpend());
					return true;
				}
			}
		}
	}
	else
	{
		if(BB->isBuildUnit(BWAPI::UnitTypes::Terran_Marine) )
		{
			DEBUG_PRINT("BuildMarine(%p) %s checked conditions and has %d minerals to spend\n", this, GetName().c_str(), BB->GetMineralsToSpend());		
			return true;
		}
	}
	return false;
}